<template>
<div class="col-md-12">
  <div class="col-md-8">
    <my-navbar>
      <template slot="left"> 
        <button type="button" class="btn btn-default" @click.prevent="onSaveAreas">{{$t("common.save")}}</button>
        <button type="button" class="btn btn-default" @click.prevent="onModeChange">{{$t("common.reset")}}</button>
      </template> 
      <template slot="right"> 
        <input type="text" class="form-control" number v-model="split.x">
        <span>X</span>
        <input type="text" class="form-control" number v-model="split.y">
        <button type="button" class="btn btn-default" @click.prevent="onSplit">{{$t("webapp.split")}}</button>
        <button type="button" class="btn btn-default" @click.prevent="onClearAllAreas">{{$t("webapp.clear")}}</button>
      </template> 
    </my-navbar>
    <div class="col-md-12" id="lcdwall">

    </div>
  </div>
  <div class="col-md-4" v-show="toolview === 'areas'">
    <div class="area-list">
      <validator name="area">
        <form class="form-horizontal">
          <div class="form-group" v-for="area in areas">
            <label class="col-sm-2 control-label">{{$index + 1}}</label>
            <div class="col-sm-10">
              <input type="text" class="form-control" maxlength="32" v-model="area.name" @change.prevent="onAreaNameChange" :field="area._field" v-validate="{required: true, maxlength: 16, name: true}">   
              <strong class="my-error text-danger" v-if="areaNameRequired(area)">{{$t('error.required')}}</strong>
              <strong class="my-error text-danger" v-if="areaNameMaxLength(area)">{{$t('error.tooLong')}}</strong>
              <strong class="my-error text-danger" v-if="areaNameValid(area)">{{$t('error.invalidName')}}</strong>                   
            </div>
          </div>      
        </form> 
      </validator>  
    </div>
  </div>
  <div class="col-md-4"  v-show="toolview === 'modes'">
    <my-navbar>
      <template slot="left"> 
        <div class="form-group"> 
          <label class="control-label">{{$t("webapp.currMode")}}</label>
          <select class="form-control" v-model="modeName" @change.prevent="onModeChange">
            <option v-for="option in modes">{{option.name}}</option>
          </select>
        </div>
      </template> 
      <template slot="right">  
        <input type="text" class="form-control" maxlength="8" v-model="mode.name">
        <button type="button" class="btn btn-default" @click.prevent="onAddMode">
          <span class="glyphicon glyphicon-plus"></span>
        </button>
      </template> 
    </my-navbar>
    <my-table :cfg="cfg" :list="modes" :loading="false"></my-table>
  </div>
</div>
</template>

<script>
import ebus from 'libs/ebus.js'
import toast from 'libs/toast.js'
import msgbox from 'libs/msgbox.js'
import locales from './locales.js'
import {LcdwallArea} from 'libs/canvas.js'
import settings from 'share/server/settings.js'
import {printObj, readableSize, isValidName} from 'libs/utils.js'
import {mediaPhyApi, commonApi} from 'share/server/api.js'

export default {
  locales,
  props: {
    multiScreen: {
      type: Object,
      default: function() {
        return {
          x: 1,
          y: 1
        }
      }
    },
    toolview: {
      type: String,
      required: true
    }
  },
  data: function() {
    return {
      mode: {
        name: ''
      },
      area: {
        name: ''
      },
      split: {
        x: 1,
        y: 1
      },
      cfg: {
        checkable: false,
        showHead: true,
        columns: [{
          field: 'name',
          width: 'auto',
          name: this.$t("list.name")
        }, {
          field: 'areaCnt',
          width: 'auto',
          name: this.$t("list.areaCnt"),
          show: function(item) {
            return item.areas.length
          }          
        }],
        operation: {
          name: this.$t("common.operation"),
          width: 'auto',
          actions: [{
            icon: 'glyphicon glyphicon-trash',
            doClick: this.onDelMode
          }]
        }        
      },
      modeName: '',
      modes: []
    }
  },
  computed: {
    areas () {
      let mode = _.find(this.modes, {name: this.modeName})
      if (mode) {
        return mode.areas
      } else {
        return []
      }
    }
  },
  methods: {
    areaNameRequired (area) {
      return this.$area[area._field].required
    },
    areaNameMaxLength (area) {
      return this.$area[area._field].maxlength
    },
    areaNameValid (area) {
      return this.$area[area._field].name
    },
    onDelMode (item) {
      if (this.modeName === item.name) {
        this.modeName = ''
        this.onClearAllAreas()
      }
      this.modes.splice(_.indexOf(this.modes, item), 1)
      this.chooseMode()
    },
    onModeChange () {
      var mode = _.find(this.modes, {name: this.modeName})
      this.preview.drawAreas(mode.areas)
    },
    chooseMode () {
      if ((this.modes.length > 0)
       && (this.modeName === '')) {
        this.modeName = this.modes[0].name
        this.onModeChange()
      }
    },
    onAddMode () {
      if (this.mode.name === '') {
        toast.e(this, this.$t('common.fail'), this.$t('error.required'))
        return
      }
      if (!isValidName(this.mode.name)) {
        toast.e(this, this.$t('common.fail'), this.$t('error.invalidName'))
        return
      }
      let mode = _.find(this.modes, {name: this.mode.name})
      if (mode) {
        toast.e(this, this.$t('common.fail'), this.$t('error.dupName'))
        return
      }
      if (this.modes.length >= 5) {
        toast.e(this, this.$t('common.fail'), this.$t('error.reachLimit'))
        return
      }
      this.modes.splice(this.modes.length, 0, {
        name: this.mode.name,
        areas: []
      })
      this.mode.name =''
      this.chooseMode()
    },
    onAreaNameChange () {
      this.onModeChange()
      console.log(this.$area)
    },
    onSaveAreas () {
      let cfgOfAreas = this.preview.getCfgOfAreas()
      var mode = _.find(this.modes, {name: this.modeName})
      if (!mode) {
        toast.e(this, this.$t('common.fail'), this.$t('error.notFound'))
        return
      }
      mode.areas = cfgOfAreas
    },
    onClearAllAreas () {
      let areas = []
      this.preview.drawAreas(areas)
    },
    onSplit () {
      if (this.multiScreen.x % this.split.x !== 0) {
        toast.e(this, this.$t('common.fail'), this.$t('error.params'))
        return
      } 
      if (this.multiScreen.y % this.split.y !== 0) {
        toast.e(this, this.$t('common.fail'), this.$t('error.params'))
        return
      }       
      let multiScreenX = this.multiScreen.x / this.split.x
      let multiScreenY = this.multiScreen.y / this.split.y

      var areas = []
      var index = 0
      for (var i = 0; i < this.split.x; i++) {
        for (var j = 0; j < this.split.y; j++) {
          index++
          areas.push({
            name: `(${i + 1}, ${j + 1})`,
            _field: 'area' + index,
            startScreenX: multiScreenX * i,
            startScreenY: multiScreenY * j,
            multiScreenX: multiScreenX,
            multiScreenY: multiScreenY
          })
        }
      }

      this.preview.drawAreas(areas)
    },
    drawPreview (modes) {
      this.modeName = ''
      //清除原LCD的模式，添加新LCD的模式
      this.modes.splice(0, this.modes.length)
      _.forEach(modes, function(item) {
        this.modes.splice(this.modes.length, 0, item)
      }.bind(this))
      //计算显示区域
      let showWidth = window.innerWidth * 73 / 120
      let showHeight = showWidth * this.multiScreen.y * 9 / (this.multiScreen.x * 16)
      this.preview.init('lcdwall', {
        width: showWidth,
        height: showHeight,  
      })
      this.preview.drawGrid(this.multiScreen)
      this.chooseMode()
    },
    alertRestart () {
      msgbox.alert({
        title: this.$t('alert.uploadSuccess'),
        text: this.$t('alert.needRestartService') + this.$t('alert.restartNow'),
        type: "success",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        cancelButtonText: this.$t('common.cancel'),
        confirmButtonText: this.$t('common.confirm'),
        closeOnConfirm: false,
        showLoaderOnConfirm: true,       
      }, 
      function() {       
        commonApi.sendCmd('restartService') 
        setTimeout(function() {
          msgbox.close()
          location.reload(true)
        }, settings.restartWaitTime)
      }.bind(this))
    },
    onSave2Server () {
      var nullModeCnt = 0
      _.forEach(this.modes, function(item) {
        if (item.areas.length <= 0) {
          nullModeCnt++
          toast.e(this, this.$t('error.params'), `模式[${item.name}]区域数为0`)
        }
      }.bind(this))
      if (nullModeCnt > 0) {
        return
      }
      mediaPhyApi.sendCmd('setModes', {modes: this.modes}).then(function(res) {
        if (res && res.data && res.data.code === 0) {
          this.alertRestart()
        } else {
          toast.code(this, res.data)
        }          
      }.bind(this))
    }
  },
  ready () {
    this.preview = new LcdwallArea()
    ebus.on('draw-preview', this.drawPreview)
    ebus.on('on-save-to-server', this.onSave2Server)
  }
}
</script>

<style scoped>
.area-list {
  max-height: 768px;
  overflow-x: hidden;
  overflow-y: auto;
}
</style>